// 数据存储管理
class ExpenseManager {
    constructor() {
        this.records = this.loadRecords();
    }

    // 从localStorage加载记录
    loadRecords() {
        const data = localStorage.getItem('expenseRecords');
        return data ? JSON.parse(data) : [];
    }

    // 保存记录到localStorage
    saveRecords() {
        localStorage.setItem('expenseRecords', JSON.stringify(this.records));
    }

    // 添加新记录
    addRecord(record) {
        record.id = Date.now();
        record.date = record.date || new Date().toISOString().split('T')[0];
        this.records.unshift(record);
        this.saveRecords();
    }

    // 获取所有记录
    getAllRecords() {
        return this.records;
    }

    // 按条件筛选记录
    filterRecords(filters = {}) {
        let filtered = [...this.records];
        
        if (filters.category) {
            filtered = filtered.filter(r => r.category === filters.category);
        }
        
        if (filters.date) {
            filtered = filtered.filter(r => r.date === filters.date);
        }
        
        return filtered;
    }

    // 获取本月统计
    getMonthStats() {
        const now = new Date();
        const currentMonth = now.getMonth();
        const currentYear = now.getFullYear();
        
        const monthRecords = this.records.filter(record => {
            const recordDate = new Date(record.date);
            return recordDate.getMonth() === currentMonth && 
                   recordDate.getFullYear() === currentYear;
        });

        const stats = {
            income: 0,
            expense: 0,
            byCategory: {}
        };

        monthRecords.forEach(record => {
            if (record.type === 'income') {
                stats.income += parseFloat(record.amount);
            } else {
                stats.expense += parseFloat(record.amount);
                stats.byCategory[record.category] = (stats.byCategory[record.category] || 0) + parseFloat(record.amount);
            }
        });

        return stats;
    }
}

// 初始化管理器
const manager = new ExpenseManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    updateMonthStats();
    displayRecords();
    updateChart();
    document.getElementById('date').valueAsDate = new Date();
});

// 打开新增记录弹窗
function openModal() {
    document.getElementById('recordModal').classList.remove('hidden');
    document.getElementById('recordModal').classList.add('flex');
}

// 关闭新增记录弹窗
function closeModal() {
    document.getElementById('recordModal').classList.add('hidden');
    document.getElementById('recordModal').classList.remove('flex');
    document.getElementById('recordForm').reset();
}

// 处理表单提交
document.getElementById('recordForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const record = {
        type: document.querySelector('input[name="type"]:checked').value,
        amount: document.getElementById('amount').value,
        category: document.getElementById('category').value,
        note: document.getElementById('note').value,
        date: document.getElementById('date').value
    };

    manager.addRecord(record);
    closeModal();
    updateMonthStats();
    displayRecords();
    updateChart();
    
    // 显示成功提示
    showToast('记录添加成功！');
});

// 更新月度统计
function updateMonthStats() {
    const stats = manager.getMonthStats();
    document.getElementById('monthIncome').textContent = `¥${stats.income.toFixed(2)}`;
    document.getElementById('monthExpense').textContent = `¥${stats.expense.toFixed(2)}`;
    document.getElementById('monthBalance').textContent = `¥${(stats.income - stats.expense).toFixed(2)}`;
}

// 显示记录列表
function displayRecords(records = null) {
    const container = document.getElementById('recordsList');
    const displayRecords = records || manager.getAllRecords().slice(0, 10);
    
    if (displayRecords.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>暂无记录</p>
            </div>
        `;
        return;
    }

    container.innerHTML = displayRecords.map(record => `
        <div class="record-item bg-gray-50 rounded-lg p-4 fade-in">
            <div class="flex justify-between items-start">
                <div>
                    <div class="flex items-center gap-2 mb-1">
                        <span class="badge badge-${record.type}">${record.type === 'income' ? '收入' : '支出'}</span>
                        <span class="text-sm text-gray-600">${record.category}</span>
                    </div>
                    <div class="text-sm text-gray-500">${record.date}</div>
                    ${record.note ? `<div class="text-sm text-gray-600 mt-1">${record.note}</div>` : ''}
                </div>
                <div class="text-right">
                    <div class="amount-${record.type} text-lg font-semibold">
                        ${record.type === 'income' ? '+' : '-'}¥${parseFloat(record.amount).toFixed(2)}
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 筛选记录
function filterRecords() {
    const category = document.getElementById('categoryFilter').value;
    const date = document.getElementById('dateFilter').value;
    
    const filters = {};
    if (category) filters.category = category;
    if (date) filters.date = date;
    
    const filtered = manager.filterRecords(filters);
    displayRecords(filtered);
}

// 更新图表
function updateChart() {
    const ctx = document.getElementById('expenseChart').getContext('2d');
    const stats = manager.getMonthStats();
    
    // 销毁旧图表
    if (window.expenseChart) {
        window.expenseChart.destroy();
    }
    
    const categories = Object.keys(stats.byCategory);
    const amounts = Object.values(stats.byCategory);
    
    // 生成随机颜色
    const colors = [
        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', 
        '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF'
    ];
    
    window.expenseChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: categories,
            datasets: [{
                data: amounts,
                backgroundColor: colors.slice(0, categories.length),
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 15,
                        font: {
                            size: 12
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(1);
                            return `${label}: ¥${value.toFixed(2)} (${percentage}%)`;
                        }
                    }
                }
            }
        }
    });
}

// 显示提示消息
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
        setTimeout(() => toast.remove(), 300);
    }, 2000);
}

// 点击弹窗外部关闭
document.getElementById('recordModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeModal();
    }
});

// 键盘事件
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});
